<template>
  <el-dialog
    top="30px"
    width="800px"
    class="dialog-sm"
    append-to-body
    title="退费登记"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="form" :rules="rules" label-width="100px" ref="form">
      <el-form-item label="退费主体" prop="id">
        <el-input
          v-model="form.customer_name"
          class="form-control-ml"
          disabled
          v-if="!isAddEdit"
        ></el-input>
        <select-refund-customer
          v-model="form.id"
          class="form-control-ml"
          @change="handleCustomerChange"
          v-else
        ></select-refund-customer>
      </el-form-item>
      <el-form-item label="已缴金额" prop="actualWarrantFee">
        <el-input v-model="form.actualWarrantFee" class="form-control-ml" disabled>
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="缴费时间" prop="actualWarrantDate">
        <el-input v-model="form.actualWarrantDate" class="form-control-ml" disabled></el-input>
      </el-form-item>
      <el-form-item label="退费金额" prop="refund_funds">
        <el-input
          :min="0"
          type="number"
          v-model="form.refund_funds"
          v-input-number="inputOptions"
          class="form-control-ml"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="退费原因" prop="refund_reason">
        <el-input v-model="form.refund_reason" class="form-control-ml" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="附件上传" prop="apply_refund_attachment">
        <upload-oss
          multiple
          accept="image/*"
          listType="picture-card"
          ref="attachOss"
          :limit="10"
          :file-list="attachFileList"
          :on-change="handleAttachValidate"
          :on-remove="handleAttachValidate"
          :on-complete="handleImagesComplete"
        ></upload-oss>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirm" :loading="saveLoading" class="btn-long">
          完成{{ isAddEdit ? '登记' : '修改' }}
        </el-button>
        <el-button @click="handleDismiss" :loading="saveLoading" class="btn-long">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { arrayFromString } from '@vimi/utils-tool'
import { strFromOss } from '@/common/plugins/tools/format'

import SelectRefundCustomer from '@/credit/views/city/settle/refund/SelectRefundCustomer'

export default {
  components: {
    SelectRefundCustomer,
  },
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      form: {
        id: '',
        customer_name: '',
        actualWarrantFee: '',
        actualWarrantDate: '',
        refund_funds: '',
        refund_reason: '',
        // 只是为了作验证，不是真正的附件地址
        apply_refund_attachment: '',
      },
      rules: {
        id: [{ required: true, message: '请选择退费主体', trigger: 'change' }],
        actualWarrantFee: [{ required: true, message: '请填写已缴金额', trigger: 'change' }],
        actualWarrantDate: [{ required: true, message: '请填写缴费时间', trigger: 'change' }],
        refund_funds: [{ required: true, message: '请填写退费金额', trigger: 'change' }],
        refund_reason: [{ required: true, message: '请填写退费原因', trigger: 'change' }],
        apply_refund_attachment: [{ required: true, message: '请上传附件', trigger: 'change' }],
      },
      inputOptions() {
        return {
          min: 0,
          fixed: 2,
          onMin: () => this.$message.error('不能小于0'),
          onFixed: () => this.$message.error('小数点不能超过2位数'),
        }
      },
      attachFileList: [],
      saveLoading: false,
    }
  },
  computed: {
    isAddEdit() {
      return !this.editRow.id
    },
  },
  watch: {
    editRow: {
      handler: function (val) {
        this.setForm(val)
        this.copyFromRow(val)
        this.$nextTick(() => {
          const form = this.$refs.form
          if (form) form.clearValidate()
        })
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleCustomerChange(val, item) {
      this.setForm(item)
      this.copyFormSelect(item)
    },
    setForm(data) {
      this.form.actualWarrantFee = data.actual_warrant_fee
      this.form.actualWarrantDate = this.$utils.dateFormat(
        data.actual_warrant_date,
        'yyyy年MM月dd日'
      )
    },
    copyFormSelect(data) {
      const keys = ['id', 'customer_name']
      keys.forEach(key => (this.form[key] = data[key]))
    },
    copyFromRow(data) {
      const keys = ['id', 'customer_name', 'refund_funds', 'refund_reason']
      keys.forEach(key => (this.form[key] = data[key]))
      this.attachFileList = arrayFromString(data.apply_refund_attachment).map(img => ({
        name: '',
        url: img,
      }))
      this.form.apply_refund_attachment = data.id ? '1' : ''
    },
    handleImagesComplete(images) {
      const imageStr = strFromOss(images)
      this.addRefund(imageStr)
    },
    handleConfirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saveLoading = true
          this.$refs.attachOss.submit()
        } else {
          this.$message.error('输入错误，请重新输入')
        }
      })
    },
    handleDismiss() {
      this.beforeClose()
    },
    handleAttachValidate(file, fileList) {
      this.form.apply_refund_attachment = fileList.length ? '1' : ''
      this.$refs.form.validateField('apply_refund_attachment')
    },
    async addRefund(attachs) {
      const data = {
        apply_refund_attachment: attachs,
        refund_funds: this.form.refund_funds,
        refund_reason: this.form.refund_reason,
      }
      if (this.isAddEdit) {
        data.refund_status = 0
        data.apply_refund_time = this.$utils.dateFormat(new Date())
      }

      this.saveLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'credit_warrant_fee_record', this.form.id, data)
      )
      this.saveLoading = false

      const hintText = this.isAddEdit ? '登记' : '修改'
      if (!res) {
        return this.$message.error(`${hintText}失败，请重试`)
      }

      this.$message.success(`${hintText}成功`)
      this.$emit('success')
      this.beforeClose()
    },
  },
}
</script>

<style lang="scss" scoped></style>
